package com.hd.trans.ui.activity;

import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProvider;

import com.hd.trans.R;
import com.hd.trans.TranslationInterior;
import com.hd.trans.common.Constants;
import com.hd.trans.common.interf.WebTransCallback;
import com.hd.trans.db.DataBaseMgr;
import com.hd.trans.db.bean.HuDunLanguage;
import com.hd.trans.db.bean.TranslateRecord;
import com.hd.trans.framework.component.HuDunTimeoutCallback;
import com.hd.trans.framework.dialog.LanguageDialog;
import com.hd.trans.framework.dialog.LanguageDialogType;
import com.hd.trans.framework.dialog.ShareDialog;
import com.hd.trans.framework.languages.ShareResultAdapter;
import com.hd.trans.framework.tools.ThreadPoolWrapper;
import com.hd.trans.homefun.EventCode;
import com.hd.trans.limit4Use.LimitUseListener;
import com.hd.trans.network.PreferenceMgr;
import com.hd.trans.network.component.HdTranslateComponent;
import com.hd.trans.network.component.TranslateCallback;
import com.hd.trans.share.EnShareFileType;
import com.hd.trans.share.ShareTextFileManager;
import com.hd.trans.ui.base.LimitBaseActivity;
import com.hd.trans.ui.model.HomeTextModel;
import com.hd.trans.utils.ToastUtils;
import com.hd.trans.utils.TrackerForTrans;
import com.hd.trans.utils.WebTransUtil;
import com.hd.trans.widgets.ImageTextView;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Objects;

public class WebHomeActivity extends LimitBaseActivity {

    @Override
    protected int getLayoutId() {
        return R.layout.activity_web_home;
    }

    private View translateLayout;
    private View viewAlpha;
    private View begin;
    private View btnBack;
    private View exchange;
    private EditText edit;
    private TextView fromText;
    private TextView toText;
    private TextView clear;
    private TextView resultText;
    private TextView tvStartTrans;
    private ImageTextView ivContentSwitch;
    private View leftBt,rightBt;

    private SimpleDateFormat mFormat;
    private ShareTextFileManager shareMG;
    private ShareDialog shareDialog;
    private TranslateRecord translateRecord;
    private HomeTextModel mDataModel;
    private String lastTransCode;
    private String lastOriginalCode;
    private String originalText;
    private String titleName;
    private boolean isFromPage = true;
    private HdTranslateComponent mTranslateComponent;//  文本翻译组件
    private HashMap<String,String> contentMap;

    public static void open(Context context, LimitUseListener listener, String titleName) {
        setLimitListener(listener);
        Intent intent = new Intent(context, WebHomeActivity.class);
        intent.putExtra("title_name",titleName);
        context.startActivity(intent);
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        super.initViewsAndEvents(savedInstanceState);
        titleName = getIntent().getStringExtra("title_name");

        contentMap = new HashMap<>();
        //翻译插件
        mTranslateComponent = new HdTranslateComponent(this);
        getLifecycle().addObserver(mTranslateComponent);

        initView();
        initViewModel();

    }

    @Override
    protected void onStart() {
        super.onStart();
        //埋点
        TranslationInterior.getTrackerListener().view(TrackerForTrans.WEB_TRANS);
    }

    private void initView() {
        translateLayout = findViewById(R.id.result_layout);
        begin = findViewById(R.id.begin);
        viewAlpha = findViewById(R.id.view_alpha);
        resultText = findViewById(R.id.result_text);
        fromText = findViewById(R.id.tv_from);
        toText = findViewById(R.id.tv_to);
        clear = findViewById(R.id.clear_text);
        btnBack = findViewById(R.id.iv_left);
        exchange = findViewById(R.id.icon_exchange);
        edit = findViewById(R.id.input_edit);
        ivContentSwitch = findViewById(R.id.iv_content_switch);
        tvStartTrans = findViewById(R.id.tv_start_trans);
        leftBt = findViewById(R.id.left_bt);
        rightBt = findViewById(R.id.right_bt);

        edit.addTextChangedListener(mEditTextListener);
        translateLayout.setVisibility(View.GONE);
        findViewById(R.id.back).setVisibility(View.GONE);
        ((TextView) findViewById(R.id.tv_title)).setText(titleName==null?"网页翻译":titleName);
        findViewById(R.id.copy_layout).setOnClickListener(this);
        findViewById(R.id.iv_menu_full).setOnClickListener(this);
        findViewById(R.id.share_layout).setOnClickListener(this);

        leftBt.setOnClickListener(this);
        rightBt.setOnClickListener(this);
        exchange.setOnClickListener(this);
        clear.setOnClickListener(this);
        begin.setOnClickListener(this);
        btnBack.setOnClickListener(this);
        ivContentSwitch.setOnClickListener(this);

    }

    private void initViewModel() {
        mDataModel = new ViewModelProvider(this).get(HomeTextModel.class);
        /*
         *  监听页面数据变化(语言改变，翻译状态改变)
         */
        mDataModel.getLanguageFrom().observe(this, huDunLanguage -> {
            if (huDunLanguage != null) {
                fromText.setText(huDunLanguage.getName());
            }
        });
        mDataModel.getLanguageTo().observe(this, huDunLanguage -> {
            if (huDunLanguage != null) {
                toText.setText(huDunLanguage.getName());
            }
        });
        mDataModel.getTranslateState().observe(this, this::translateStateChanged);

        if(DataBaseMgr.getInstance().getDaoSession()==null){
            DataBaseMgr.init(this);
        }

        mDataModel.getOperateRecord().observe(this, record -> {
            this.translateRecord = record;
            mDataModel.setLanguageFrom(record.getLanguageFrom());
            mDataModel.setLanguageTo(record.getLanguageTo());
            mDataModel.setTranslateState(Constants.TRANSLATED);
            viewAlpha.setVisibility(View.VISIBLE);

            resultText.setText(record.getContentTranslate());
            ivContentSwitch.setText(getResources().getString(R.string.view_original_text));
        });

        String fromLangName = PreferenceMgr.getInstance().getTranslatePreference().getTansFromLanguage();
        String toLangName = PreferenceMgr.getInstance().getTranslatePreference().getTansToLanguage();
        mDataModel.setLanguageFrom(DataBaseMgr.getInstance().getLanguageByName(fromLangName));
        mDataModel.setLanguageTo(DataBaseMgr.getInstance().getLanguageByName(toLangName));
        mDataModel.setTranslateState(Constants.TRANSLATE_NORMAL);
    }

    /**
     * 当前状态改变
     */
    private void translateStateChanged(int translateState) {
        switch (translateState) {
            case Constants.TRANSLATE_NORMAL://未翻译
                begin.setEnabled(true);
                clear.setEnabled(true);
                edit.setEnabled(true);
                translateLayout.setVisibility(View.GONE);
                viewAlpha.setVisibility(View.GONE);

                if(tvStartTrans.getText().toString().equals(getResources().getString(R.string.restart_translating))){
                    tvStartTrans.setText(getResources().getString(R.string.start_translating));
                }
                break;
            case Constants.TRANSLATING://翻译中
                begin.setEnabled(false);
                clear.setEnabled(false);
                edit.setEnabled(false);
                //翻译中禁止操作和更改原内容
                break;
            case Constants.TRANSLATED://已翻译
                begin.setEnabled(true);
                edit.setEnabled(true);
                clear.setEnabled(true);
                translateLayout.setVisibility(View.VISIBLE);
                if(tvStartTrans.getText().toString().equals(getResources().getString(R.string.start_translating))){
                    tvStartTrans.setText(getResources().getString(R.string.restart_translating));
                }
                break;
        }
    }

    /**
     * 清空
     */
    private void clearAll() {
        clearFrom();
        clearTo();
    }

    /**
     * 清空From
     */
    private void clearFrom() {
        edit.setText("");
    }

    /**
     * 清空To
     */
    private void clearTo() {
        resultText.setText("");
    }

    //选择语言弹框
    private void showSelectLanguageDialog() {
       /* SelectLanguageDialog.newInstance(mDataModel.getLanguageFrom().getValue(), mDataModel.getLanguageTo().getValue(), isFromPage, false, false)
                .setOnLanguageChangedListener((language, isFrom) -> {
                    if (isFrom) {
                        mDataModel.setLanguageFrom(language);
                    } else {
                        mDataModel.setLanguageTo(language);
                    }
                    mDataModel.setTranslateState(Constants.TRANSLATE_NORMAL);
                }).show(getSupportFragmentManager(), "TextHomeActivity");*/

        LanguageDialog dialog = new LanguageDialog(
                Objects.requireNonNull(mDataModel.getLanguageFrom().getValue()),
                Objects.requireNonNull(mDataModel.getLanguageTo().getValue()),
                isFromPage, LanguageDialogType.TEXT, LanguageDialogType.TO_TEXT);
        dialog.show(getSupportFragmentManager(),"LanguageDialog");
        dialog.setOnLanguageChangedListener((fromLanguage, toLanguage, selectedLanguage) -> {
            mDataModel.setLanguageFrom(fromLanguage);
            PreferenceMgr.getInstance().getTranslatePreference().saveTansFromLanguage(fromLanguage.getName());
            mDataModel.setLanguageTo(toLanguage);
            PreferenceMgr.getInstance().getTranslatePreference().saveTansToLanguage(toLanguage.getName());
        });
    }

    private boolean isLimit4Use(EventCode code) {
        return !intercept(code);
    }

    private void success() {
        consumeFreeTrial();
    }

    /**
     * 执行web网址解析
     */
    private void parseTextByUrl(String url) {
        showLoadDialog("处理中...", new HuDunTimeoutCallback(5000) {
            @Override
            public void onTimeOut() {
                hideLoadDialog();
            }
        },null);

        if(contentMap.containsKey(url)){
            executeTranslate(contentMap.get(url));
            return;
        }

        ThreadPoolWrapper.getInstance().excuseThread(() -> {
            WebTransUtil.parseTextByUrl(url, new WebTransCallback() {
                @Override
                public void parseTextCallback(String text) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if(TextUtils.isEmpty(text)){
                                hideLoadDialog();
                                ToastUtils.showNormal("查找网址内容为空");
                                return;
                            }
                            contentMap.put(url, text);
                            executeTranslate(text);
                        }
                    });
                }

                @Override
                public void parseFailed(String msg) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            hideLoadDialog();
                            ToastUtils.showNormal(msg);
                        }
                    });
                }
            });
        });
    }

    /**
     * 执行文本翻译
     */
    /**
     * 执行翻译  参考项目原有逻辑。
     */
    private void executeTranslate(String origContent) {
        if (TextUtils.isEmpty(origContent)){

            return;
        }
        if(mDataModel.getLanguageTo().getValue() == null
                || mDataModel.getLanguageFrom().getValue() == null){
            return;
        }
        //如果最后请求原文和最后请求目标语言都一致则不请求接口，从历史数据获取并展示
        if (origContent.equals(originalText)) {
            if (mDataModel.getLanguageTo().getValue().getTranslateCode().equals(lastTransCode)
                    && mDataModel.getLanguageFrom().getValue().getTranslateCode().equals(lastOriginalCode)) {
                hideLoadDialog();
                WebHomeActivity.this.mDataModel.setOperateRecord(translateRecord);
                ToastUtils.showNormal(R.string.fanyi_success_tip);
                return;
            }
        }


        //记录下最后请求的目标语言
        lastTransCode = this.mDataModel.getLanguageTo().getValue().getTranslateCode();
        lastOriginalCode = this.mDataModel.getLanguageFrom().getValue().getTranslateCode();
        mTranslateComponent.translationText(this,origContent,
                this.mDataModel.getLanguageFrom().getValue().getTranslateCode(),
                this.mDataModel.getLanguageTo().getValue().getTranslateCode(),false,
                new TranslateCallback() {
                    @Override
                    public void onTranslateFailed(int code, String msg) {
                        originalText = "";
                        hideLoadDialog();
                        WebHomeActivity.this.mDataModel.setTranslateState(Constants.TRANSLATE_NORMAL);
                        if(code == Constants.ResponseCode.ERROR_IS_DANGER
                                || code == Constants.ResponseCode.ERROR_COMM){
                            ToastUtils.showError(msg);
                        }else {
                            ToastUtils.showError(R.string.fanyi_faith_tip);
                        }
                    }

                    @Override
                    public void onTranslateCompleted(
                            String data,
                            String fromLangCode,
                            String toLangCode,
                            boolean status) {
                        //记录下最后请求的原文
                        originalText = origContent;
                        hideLoadDialog();
                        TranslateRecord record = new TranslateRecord();
                        record.setIsVoice(false);
                        record.setIsNation(false);
                        record.setIsCollected(false);
                        record.setLanguageFrom(WebHomeActivity.this.mDataModel.getLanguageFrom().getValue());
                        record.setLanguageTo(WebHomeActivity.this.mDataModel.getLanguageTo().getValue());
                        record.setContentOrig(origContent);
                        record.setContentTranslate(data);
                        record.setTriggerTime(System.currentTimeMillis());
                        //重复数据。就删除前面的历史数据
                        DataBaseMgr instance = DataBaseMgr.getInstance();
                        instance.isContain(record);
                        instance.addTranslateRecord(record);

                        //翻译成功。回调给app端
                        success();
                        //埋点，翻译结果+1
                        TranslationInterior.getTrackerListener().click(TrackerForTrans.WEB_TRANS , TrackerForTrans.TRANS_JG);

                        WebHomeActivity.this.mDataModel.setOperateRecord(record);

                    }
                });
    }

    private String getContent(){
        String content = resultText.getText().toString();
        if(TextUtils.isEmpty(content)){
            ToastUtils.showNormal("文本内容为空");
        }
        return content;
    }

    private boolean shareWord() {
        String content = getContent();
        if(TextUtils.isEmpty(content))return false;
        shareMG.shareTextFile(content, shareFileName() + ".doc", EnShareFileType.WORD_FILE);
        return true;
    }

    private boolean shareTxt() {
        String content = getContent();
        if(TextUtils.isEmpty(content))return false;
        shareMG.shareTextFile(content, shareFileName(), EnShareFileType.TXT_FILE);
        return true;
    }

    private boolean sharePdf() {
        String content = getContent();
        if(TextUtils.isEmpty(content))return false;
        shareMG.shareTextFile(content, shareFileName() + ".pdf", EnShareFileType.PDF_FILE);
        return true;
    }

    public String shareFileName() {
        if (null == mFormat)
            mFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
        return mFormat.format(new Date().getTime());
    }

    /**
     * 输入框监听
     */
    private final TextWatcher mEditTextListener = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            if (!TextUtils.isEmpty(s)) {

                if(clear.getCurrentTextColor() == getResources().getColor(R.color.color_9DA9B9)){
                    clear.setTextColor(getResources().getColor(R.color.color_282A43));
                }
                viewAlpha.setVisibility(View.GONE);
            } else {
                if (Constants.TRANSLATE_NORMAL != mDataModel.getTranslateState().getValue()) {
                    mDataModel.setTranslateState(Constants.TRANSLATE_NORMAL);
                }
                if(clear.getCurrentTextColor() == getResources().getColor(R.color.color_282A43)){
                    clear.setTextColor(getResources().getColor(R.color.color_9DA9B9));
                }
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        contentMap.clear();
        mDataModel.getTranslateState().removeObservers(this);
        mDataModel.getLanguageFrom().removeObservers(this);
        mDataModel.getLanguageTo().removeObservers(this);
        getLifecycle().removeObserver(mTranslateComponent);
    }

    @Override
    public void onViewClick(View v) {
        int viewId = v.getId();
        if(viewId == R.id.iv_left){
            finish();
        }else if(viewId == R.id.left_bt){
            isFromPage = true;
            showSelectLanguageDialog();
        }else if(viewId == R.id.right_bt){
            isFromPage = false;
            showSelectLanguageDialog();
        }else if(viewId == R.id.icon_exchange){//语种互换
            showTranslateAnimation();
        }else if (viewId == R.id.begin) {//开始执行翻译
            if(isLimit4Use(EventCode.WEB_TRANS)){
                parseTextByUrl(edit.getText().toString().trim().replace("\\S",""));
            }
            TranslationInterior.getTrackerListener().click(TrackerForTrans.WEB_TRANS, TrackerForTrans.START_TRANS);
        }else if(viewId == R.id.clear_text){//清空链接
            clearAll();
            mDataModel.setTranslateState(Constants.TRANSLATE_NORMAL);
            TranslationInterior.getTrackerListener().click(TrackerForTrans.WEB_TRANS, TrackerForTrans.CLEAR_URL);
        }else if(viewId == R.id.iv_content_switch){//查看原文or查看译文
            if(translateRecord == null)return;
            if(ivContentSwitch.getText().equals(getResources().getString(R.string.view_original_text))){
                ivContentSwitch.setText(getResources().getString(R.string.view_trans_text));
                resultText.setText(translateRecord.getContentOrig());
            }else {
                resultText.setText(translateRecord.getContentTranslate());
                ivContentSwitch.setText(getResources().getString(R.string.view_original_text));
            }
        }else if (viewId == R.id.iv_menu_full) {//全屏显示
            String content = getContent();
            if(TextUtils.isEmpty(content))return;

            TranslationInterior.getTrackerListener().click(TrackerForTrans.WEB_TRANS,TrackerForTrans.QuanPing);
            Intent intent = new Intent(getActivity(), FullScreenActivity.class);
            intent.putExtra("content", content);
            startActivity(intent);
        }else if (viewId == R.id.share_layout) {//分享
            TranslationInterior.getTrackerListener().click(TrackerForTrans.WEB_TRANS,TrackerForTrans.FenXiang);

            if (null == shareDialog) {
                shareDialog = ShareDialog.builder()
                        .setButtonColor(TranslationInterior.getThemeColor())
                        .setItemClickListenner(new ShareDialog.OnShareItemClickListenner() {
                            @Override
                            public void OnItemClick(Dialog dialog, ShareResultAdapter adapter, int position) {
                                if (shareMG == null) {
                                    shareMG = new ShareTextFileManager(getActivity());
                                }
                                switch (position) {
                                    case 0: //导出Word
                                        if (isLimit4Use(EventCode.TEXT_SHARE_WORD)) {
                                            shareWord();
                                        }
                                        break;
                                    case 1://导出TXT
                                        if (isLimit4Use(EventCode.TEXT_SHARE_TXT)) {
                                            shareTxt();
                                        }
                                        break;
                                    case 2://导出PDF
                                        if (isLimit4Use(EventCode.TEXT_SHARE_PDF)) {
                                            sharePdf();
                                        }
                                        break;
                                }
                                dialog.dismiss();
                            }
                        }).build(false);
            }
            shareDialog.show(getSupportFragmentManager(), "WebHomeActivity");
        }else if (viewId == R.id.copy_layout) {//复制
            TranslationInterior.getTrackerListener().click(TrackerForTrans.WEB_TRANS,TrackerForTrans.FuZhi);
            if (isLimit4Use(EventCode.TEXT_COPY)) {
                String content = getContent();
                if(TextUtils.isEmpty(content))return;
                ClipboardManager cmb = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                ClipData mClipData = ClipData.newPlainText("翻译结果", content);
                cmb.setPrimaryClip(mClipData);
                ToastUtils.showNormal(getResources().getString(R.string.copy_success_tips));
                //Toast.makeText(this, "结果已复制", Toast.LENGTH_SHORT).show();
            }

        }

    }

    /**
     * 互换语种动画
     */
    private void showTranslateAnimation() {
        if("自动检测".equals(mDataModel.getLanguageFrom().getValue().getName())){
            ToastUtils.showNormal(getResources().getString(R.string.tips_to_not_auto));
            return;
        }
        TranslateAnimation ta1 = new TranslateAnimation(0, leftBt.getWidth() + exchange.getWidth(), 0, 0);
        ta1.setDuration(600);
        ta1.setFillAfter(true);
        leftBt.startAnimation(ta1);
        leftBt.bringToFront();

        TranslateAnimation ta2 = new TranslateAnimation(0, -rightBt.getWidth()-exchange.getWidth(), 0, 0);
        ta2.setDuration(600);
        ta2.setFillAfter(true);
        rightBt.startAnimation(ta2);
        rightBt.bringToFront();

        ta1.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                HuDunLanguage fromTemp = mDataModel.getLanguageFrom().getValue();
                mDataModel.setLanguageFrom(mDataModel.getLanguageTo().getValue());
                mDataModel.setLanguageTo(fromTemp);
                mDataModel.setTranslateState(Constants.TRANSLATE_NORMAL);
                animation.cancel();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        ta2.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                animation.cancel();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    @NonNull
    @Override
    public EventCode getPageType() {
        return EventCode.WEB_TRANS;
    }
}
